package cn.bytecollege.merchant.controller;

import cn.bytecollege.common.entity.Merchant;
import cn.bytecollege.common.util.MD5Util;
import cn.bytecollege.merchant.service.MerchantService;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "MerchantLoginController",value = "/merchant/login")
public class MerchantLoginController extends HttpServlet {
    private MerchantService merchantService = null;
    public MerchantLoginController(){
        merchantService = new MerchantService();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       request.getRequestDispatcher("/admin/merchantLogin.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String msg = null;
        //获取表单数据
        String merchantname = request.getParameter("merchantname");
        String password = request.getParameter("password");
        String validCode = request.getParameter("valid");

        //获取数据库的merchantname
        Merchant merchant = merchantService.findMerchantByMerchantname(merchantname);
        if (merchant == null){
            //用户名不存在
            msg="没有该商家";
            request.setAttribute("msg",msg);
            request.getRequestDispatcher("/admin/merchantLogin.jsp").forward(request,response);
            return;
        }
        //判断用户名和密码是否相同
        if(MD5Util.md5Encode(password).equals(merchant.getMerchantPassword())&&merchantname.equals(merchant.getMerchantName())){
            HttpSession session = request.getSession();
            session.setMaxInactiveInterval(10*60); //10乘以1min，存活时间10min。
            session.setAttribute("merchant",merchant);

            response.sendRedirect(request.getContextPath()+"/admin/index.jsp");
        }else{
            msg="账户或者密码错误";
            request.setAttribute("msg",msg);
            request.getRequestDispatcher("/admin/merchantLogin.jsp").forward(request,response);
        }
    }
}
